#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mpv/client.h>

#include "libmpv.h"
#include "parse.h"

int
parse(char *buf)
{
	char *token = NULL;

	if (!buf) {
		fprintf(stderr, "parse: argument is NULL.\n");
		return -1;
	}

	token = strtok(buf, " \n");
	do {
		if (!strcmp("play", token)) {
			token = strtok(NULL, "\n");
			if (!token) {
				fprintf(stderr, "mpvd play: missing filename…\n");
				continue;
			}
			fprintf(stderr, "mpvd play %s\n", token);
			libmpv_play(token);
/* 			printf("%s\n", token);
 */
		} else if (!strcmp("queue", token)) {
			token = strtok(NULL, "\n");
			if (!token) {
				fprintf(stderr, "mpvd queue: missing filename…\n");
				continue;
			}
			fprintf(stderr, "mpvd queue %s\n", token);
			libmpv_queue(token);
/* 			printf("mpvd queue add %s\n", token);
 */
		} else if (!strcmp("next", token)) {
			fprintf(stderr, "mpvd next\n");
			libmpv_next();
		} else if (!strcmp("prev", token)) {
			fprintf(stderr, "mpvd prev\n");
			libmpv_prev();
		} else if (!strcmp("stop", token)) {
			fprintf(stderr, "mpvd stop\n");
			libmpv_stop();
		} else if (!strcmp("keypress", token)) {
			token = strtok(NULL, "\n");
			if (!token) {
				fprintf(stderr, "mpvd keypress: missing argument…\n");
				continue;
			}
			fprintf(stderr, "mpvd keypress %s\n", token);
			libmpv_keypress(token);
		} else if (!strcmp("quit", token)) {
			fprintf(stderr, "mpvd quit\n");
			exit(EXIT_SUCCESS);
		} else {
			fprintf(stderr, "invalid command: \"%s\"\n", token);
		}
	} while ((token = strtok(NULL, " \n")));

	fflush(stdout);

	return 0;
}
